package com.upcode.weighing.utils;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/** 
 * doc docx格式转换 
 */
@Slf4j
public class Word2PdfUtil {



    public File getPdfFile() {
        return pdfFile;
    }

    private String fileName;
    private File pdfFile;
    private File docFile;

    private String ADDRESS;


    public Word2PdfUtil(String ADDRESS,String fileString) {
        this.ADDRESS = ADDRESS;
        ini(fileString);
    }

    /** 
     * 重新设置file 
     *  
     * @param fileString 
     */  
    public void setFile(String fileString) {  
        ini(fileString);  
    }  
  
    /** 
     * 初始化
     * @param fileString 
     */  
    private void ini(String fileString) {  
        log.info("【初始化转换PDF的word文件】 - 源文件路径：{}",fileString);
        fileName = fileString.substring(0, fileString.lastIndexOf("."));
        log.info("【初始化转换PDF的word文件】 - pdf 文件路劲：{}",fileName + ".pdf");
        docFile = new File(fileString);  
        pdfFile = new File(fileName + ".pdf");
    }  
      
    /** 
     * 转为PDF 
     *
     */  
    public void doc2pdf() throws Exception {
        if (docFile.exists()) {  
            if (!pdfFile.exists()) {
                OpenOfficeConnection connection = new SocketOpenOfficeConnection(ADDRESS,8100);
                try {  
                    connection.connect();  
                    DocumentConverter converter = new OpenOfficeDocumentConverter(connection);  
                    converter.convert(docFile, pdfFile);  
                    // close the connection  
                    connection.disconnect();  
                    System.out.println("****pdf转换成功，PDF输出：" + pdfFile.getPath()+ "****");  
                } catch (java.net.ConnectException e) {  
                    e.printStackTrace();  
                    System.out.println("****swf转换器异常，openoffice服务未启动！****");  
                    throw e;  
                } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {  
                    e.printStackTrace();  
                    System.out.println("****swf转换器异常，读取转换文件失败****");  
                    throw e;  
                } catch (Exception e) {  
                    e.printStackTrace();  
                    throw e;  
                }  
            } else {  
                System.out.println("****已经转换为pdf，不需要再进行转化****");  
            }  
        } else {  
            System.out.println("****swf转换器异常，需要转换的文档不存在，无法转换****");  
        }  
    }  

  
}
